﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.Text.RegularExpressions;

namespace biolit_config
{

    internal class Ontologies
    {
        RestClient rc = new RestClient();
        // TO DO USE CONFIG
        // old URL "http://ncbo-core-prod1.stanford.edu:8080/bioportal/rest/ontologies"
        //private string URL = "http://rest.bioontology.org/bioportal/ontologies";
        private string URL = Biolit_Settings.Settings.SelectedDownloadURL.URL;
        #region public methods

        /// <summary>
        /// GetOntologies - Populate ontologies from URL
        /// </summary>
        
        public Dictionary<string, string> GetOntologies()
        {
            Dictionary<string, string> Ontologies = new Dictionary<string, string>();

            //string OntologyXML = rc.GET(URL);
            string Status = null;
            string OntologyXML = rc.GET(Biolit_Settings.Settings.MainURL, ref Status);

            if (OntologyXML != null)
            {
                //TO DO USE CONFIG
                MatchCollection mc = Regex.Matches(OntologyXML, @"<id>(.*?)</id>.*?<displayLabel>(.*?)</displayLabel>");
                foreach (Match m in mc)
                {
                    if (Ontologies.ContainsKey(m.Groups[2].Value) != true)
                        Ontologies.Add(m.Groups[2].Value, m.Groups[1].Value);
                }
            }

            return Ontologies;            
        }

        /// <summary>
        /// DownloadOntology - Retrieve a specific ontology from the URL
        /// </summary>
        public void DownloadOntology(OntList ont, string DownloadPath, ref string Status, ref string Size)
        {
            try
            {
                //string url = URL + @"/download/" + ont.ID;
                string url = URL + @"/" + ont.ID + @"?apikey=bd750df3-3ec6-4383-b506-6ad887cfdcd1";
                string ontData = rc.GET(url, ref Status);

                if (ontData != null)
                {
                    string FileName = ont.Name + @"." + ont.Format.ToLower();
                    File.WriteAllText(Path.Combine(DownloadPath, FileName), ontData);
                    if (File.Exists(Path.Combine(DownloadPath, FileName)))
                    {
                        FileInfo fi = new FileInfo(Path.Combine(DownloadPath, FileName));
                        if (fi.Length > 0)
                            Size = ToByteString(fi.Length);
                        else
                            Size = "0 Bytes";
                    }
                    
                }
            }
            catch (Exception ex)
            {

            }
        }

        public static string ToByteString(long bytes)
        {
            long KB = 1024;
	        long MB = 1024 * KB;
	        long GB = 1024 * MB;
	        long TB = 1024 * GB;
            if (bytes > TB) return (bytes / TB).ToString("0.00 TB");
            else if (bytes > GB) return (bytes / GB).ToString("0.00 GB");
            else if (bytes > MB) return (bytes / MB).ToString("0.00 MB");
            else if (bytes > KB) return (bytes / KB).ToString("0.00 KB");
            else return bytes + " Bytes";
        }

        #endregion public methods
    }
    
    
    public class RestClient
    {

        #region public methods
        /// <summary>
        /// RestClient - empty constructor
        /// </summary>
        public RestClient()
        {
            
        }

        /// <summary>
        /// GET - handles REST interaction with given URL
        /// <param name="url"></param>
        /// </summary>
        public string GET(string url, ref string status)
        {
            HttpWebResponse WebResp = null;
            string strRet = null;

            try
            {
                HttpWebRequest httpRequest;
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
                httpRequest.Method = "GET";
                WebResp = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (Exception ex)
            {
                if( ex.GetType().Equals(typeof(WebException)) ){
                    // let the user know that the URL did not work - perhaps there is no connection or the URL is incorrect
                    //MessageBox.Show("Ontology could not be downloaded from "+url+" because of error \""+ex.Message+"\"", "BioLit Error", MessageBoxButtons.OK);
                    status = ex.Message;
                }

                return null;
            }

            if (WebResp != null)
            {
                Stream RespStream = WebResp.GetResponseStream();
                StreamReader ResponseText = new StreamReader(RespStream);
                strRet = ResponseText.ReadToEnd();
                WebResp.Close();
            }

            return strRet;
        }


        public string GET(string url)
        {
            HttpWebResponse WebResp = null;
            string strRet = null;

            try
            {
                HttpWebRequest httpRequest;
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
                httpRequest.Method = "GET";
                WebResp = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (Exception ex)
            {
                if (ex.GetType().Equals(typeof(WebException)))
                {
                    // let the user know that the URL did not work - perhaps there is no connection or the URL is incorrect
                  MessageBox.Show("Ontology could not be downloaded from "+url+" because of error \""+ex.Message+"\"", "BioLit Error", MessageBoxButtons.OK);
         
                }

                return null;
            }

            if (WebResp != null)
            {
                Stream RespStream = WebResp.GetResponseStream();
                StreamReader ResponseText = new StreamReader(RespStream);
                strRet = ResponseText.ReadToEnd();
                WebResp.Close();
            }

            return strRet;
        }
        #endregion public methods
    }
}
